<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card class="filter-container">
      <el-form :inline="true" :model="queryParams" ref="queryForm">
        <el-form-item label="教师姓名">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入教师姓名"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="教师状态">
          <el-select v-model="queryParams.status" placeholder="教师状态" clearable style="width: 150px;">
            <el-option label="正常" value="1" />
            <el-option label="禁用" value="0" />
            <el-option label="全部" value="" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区 -->
    <el-card class="table-container">
      <template #header>
        <div class="card-header">
          <el-button type="primary" @click="handleAdd">新增教师</el-button>
          <el-button type="danger" :disabled="!selectedIds.length" @click="handleBatchDelete">
            批量删除
          </el-button>
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="teacherList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="教师姓名" prop="name" />
        <el-table-column label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :src="row.avatar" :size="40"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column label="手机号" prop="teacherCertification.phone" width="120" />
        <el-table-column label="邮箱" prop="teacherCertification.email" width="180" />
        <el-table-column label="职称" prop="title" width="100" />
        <el-table-column label="专业" prop="subject" width="120" />
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <StatusTag :status="row.status" type="normal" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createdAt" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button
              link
              :type="row.status === 1 ? 'warning' : 'success'"
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="700px"
      append-to-body
    >
      <el-form
        ref="teacherFormRef"
        :model="teacherForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="teacherForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="'/upload/teacher-avatar'"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
          >
            <img v-if="teacherForm.avatar" :src="teacherForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="teacherForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="teacherForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="职称" prop="title">
          <el-select v-model="teacherForm.title" placeholder="请选择职称">
            <el-option label="讲师" value="讲师" />
            <el-option label="副教授" value="副教授" />
            <el-option label="教授" value="教授" />
            <el-option label="高级讲师" value="高级讲师" />
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="subject">
          <el-input v-model="teacherForm.subject" placeholder="请输入专业" />
        </el-form-item>
        <el-form-item label="简介" prop="introduction">
          <el-input
            v-model="teacherForm.introduction"
            type="textarea"
            :rows="4"
            placeholder="请输入简介"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="teacherForm.status">
            <el-radio label="normal" value="1">正常</el-radio>
            <el-radio label="disabled" value="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getTeacherList, addTeacher, updateTeacher, deleteTeacher, toggleTeacherStatus } from '@/api/teacher'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  status: ''
})

// 数据列表
const teacherList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedIds = ref([])

// 对话框控制
const dialog = reactive({
  visible: false,
  title: ''
})

// 表单对象
const teacherForm = reactive({
  id: undefined,
  name: '',
  avatar: '',
  phone: '',
  email: '',
  title: '',
  subject: '',
  introduction: '',
  status: '1'
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请选择职称', trigger: 'change' }
  ]
}

// 文件上传配置
const uploadUrl = import.meta.env.VITE_API_BASE_URL + '/upload'

// 获取数据列表
const getList = async () => {
  try {
    loading.value = true
    await getTeacherList(queryParams).then(res=>{
      teacherList.value = res.data.records
      total.value = res.data.total
    })

  } catch (error) {
    console.error('获取教师列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.name = ''
  queryParams.status = ''
  handleQuery()
}

// 选择项变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增教师
const handleAdd = () => {
  dialog.title = '新增教师'
  dialog.visible = true
  teacherForm.id = undefined
  teacherForm.name = ''
  teacherForm.avatar = ''
  teacherForm.phone = ''
  teacherForm.email = ''
  teacherForm.title = ''
  teacherForm.subject = ''
  teacherForm.introduction = ''
  teacherForm.status = 'normal'
}

// 编辑教师
const handleEdit = (row) => {
  dialog.title = '编辑教师'
  dialog.visible = true
  Object.assign(teacherForm, row)
}

// 提交表单
const submitForm = async () => {
  try {
    if (teacherForm.id) {
      await updateTeacher(teacherForm)
      ElMessage.success('修改成功')
    } else {
      await addTeacher(teacherForm)
      ElMessage.success('新增成功')
    }
    dialog.visible = false
    getList()
  } catch (error) {
    console.error('保存教师失败:', error)
  }
}

// 删除教师
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该教师吗？', '警告', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteTeacher(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除教师失败:', error)
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择要删除的教师')
    return
  }
  ElMessageBox.confirm(`确认要删除选中的 ${selectedIds.value.length} 个教师吗？`, '警告', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteTeacher(selectedIds.value)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('批量删除失败:', error)
    }
  })
}

// 切换教师状态
const handleToggleStatus = async (row) => {
  try {
    await toggleTeacherStatus(row.id)
    ElMessage.success('操作成功')
    getList()
  } catch (error) {
    console.error('切换状态失败:', error)
  }
}

// 上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 上传成功回调
const handleUploadSuccess = (response) => {
  teacherForm.avatar = response.data
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

// 页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .filter-container {
    margin-bottom: 20px;
  }

  .table-container {
    .card-header {
      display: flex;
      justify-content: flex-start;
      align-items: center;
    }
  }

  .avatar-uploader {
    .avatar {
      width: 100px;
      height: 100px;
      display: block;
      border-radius: 50%;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      text-align: center;
      border: 1px dashed #d9d9d9;
      border-radius: 50%;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
